package platform

import (
	"net/http"
	"strconv"
	"strings"
	"time"

	"gitee.com/wangshh_123/cross-pay-go/src/errors"
	"gitee.com/wangshh_123/cross-pay-go/src/middleware"
	"gitee.com/wangshh_123/cross-pay-go/src/platform/common"
	"gitee.com/wangshh_123/cross-pay-go/src/platform/integration"
	commonUtils "gitee.com/wangshh_123/cross-pay-go/src/utils/common"
	"github.com/gin-gonic/gin"
)

// CardHistoryController 卡历史控制器
type CardHistoryController struct {
	platformManager *integration.PlatformManager
}

// NewCardHistoryController 创建卡历史控制器
func NewCardHistoryController() *CardHistoryController {
	return &CardHistoryController{
		platformManager: integration.GetGlobalPlatformManager(),
	}
}

// validateAndGetPaginationParams 验证并获取分页参数
func (c *CardHistoryController) validateAndGetPaginationParams(ctx *gin.Context) (int64, int64, error) {
	pageIndexStr := ctx.DefaultQuery("pageIndex", "1")
	pageSizeStr := ctx.DefaultQuery("pageSize", "10")

	pageIndex, err := strconv.ParseInt(pageIndexStr, 10, 64)
	if err != nil || pageIndex < 1 {
		return 0, 0, errors.NewAppError(http.StatusBadRequest, "invalid_page_index", err)
	}

	pageSize, err := strconv.ParseInt(pageSizeStr, 10, 64)
	if err != nil || pageSize < 1 || pageSize > 100 {
		return 0, 0, errors.NewAppError(http.StatusBadRequest, "invalid_page_size", err)
	}

	return pageIndex, pageSize, nil
}

// validatePlatform 验证平台类型
func (c *CardHistoryController) validatePlatform(platformType string) error {
	supportedPlatforms := []string{"photonpay", "hlpay"}
	for _, platform := range supportedPlatforms {
		if platform == platformType {
			return nil
		}
	}
	return errors.NewAppError(http.StatusBadRequest, "unsupported_platform", nil)
}

// validateQueryParams 验证查询参数
func (c *CardHistoryController) validateQueryParams(ctx *gin.Context) error {
	// 验证卡ID长度
	if cardID := ctx.Query("cardId"); cardID != "" && len(cardID) > 50 {
		return errors.NewAppError(http.StatusBadRequest, "card_id_too_long", nil)
	}

	// 验证状态参数 - 支持更多状态值
	if status := ctx.Query("status"); status != "" {
		validStatuses := []string{
			"success", "succeed", "completed", "active",
			"failed", "error", "rejected", "cancelled",
			"pending", "processing", "waiting",
			"closed", "inactive", "suspended",
		}
		isValid := false
		for _, validStatus := range validStatuses {
			if strings.ToLower(status) == validStatus {
				isValid = true
				break
			}
		}
		if !isValid {
			return errors.NewAppError(http.StatusBadRequest, "invalid_status", nil)
		}
	}

	// 验证费用类型
	if feeType := ctx.Query("feeType"); feeType != "" {
		validFeeTypes := []string{
			"transaction", "monthly", "annual", "setup",
			"create_card_fee", "maintenance_fee", "service_fee",
			"activation_fee", "replacement_fee",
		}
		isValid := false
		for _, validFeeType := range validFeeTypes {
			if strings.ToLower(feeType) == validFeeType {
				isValid = true
				break
			}
		}
		if !isValid {
			return errors.NewAppError(http.StatusBadRequest, "invalid_fee_type", nil)
		}
	}

	// 验证日期格式
	if createdAtStart := ctx.Query("createdAtStart"); createdAtStart != "" {
		if _, err := time.Parse("2006-01-02", createdAtStart); err != nil {
			if _, err := time.Parse("2006-01-02T15:04:05", createdAtStart); err != nil {
				return errors.NewAppError(http.StatusBadRequest, "invalid_start_date_format", nil)
			}
		}
	}

	if createdAtEnd := ctx.Query("createdAtEnd"); createdAtEnd != "" {
		if _, err := time.Parse("2006-01-02", createdAtEnd); err != nil {
			if _, err := time.Parse("2006-01-02T15:04:05", createdAtEnd); err != nil {
				return errors.NewAppError(http.StatusBadRequest, "invalid_end_date_format", nil)
			}
		}
	}

	// 验证日期范围
	if createdAtStart := ctx.Query("createdAtStart"); createdAtStart != "" {
		if createdAtEnd := ctx.Query("createdAtEnd"); createdAtEnd != "" {
			startTime, _ := time.Parse("2006-01-02", createdAtStart)
			endTime, _ := time.Parse("2006-01-02", createdAtEnd)
			if startTime.After(endTime) {
				return errors.NewAppError(http.StatusBadRequest, "start_date_after_end_date", nil)
			}
		}
	}

	return nil
}

// buildCardHistoryRequest 构建卡历史请求参数
func (c *CardHistoryController) buildCardHistoryRequest(ctx *gin.Context, pageIndex, pageSize int64) *common.CardHistoryListRequest {
	return &common.CardHistoryListRequest{
		PageIndex:      pageIndex,
		PageSize:       pageSize,
		CardID:         ctx.Query("cardId"),
		CardFormFactor: ctx.Query("cardFormFactor"),
		Status:         ctx.Query("status"),
		FeeType:        ctx.Query("feeType"),
		CreatedAtStart: ctx.Query("createdAtStart"),
		CreatedAtEnd:   ctx.Query("createdAtEnd"),
	}
}

// GetCardHistoryList 获取卡历史列表
func (c *CardHistoryController) GetCardHistoryList(ctx *gin.Context) {
	// 从中间件获取平台信息
	platformInfo, exists := middleware.GetPlatformInfoFromContext(ctx)
	if !exists {
		commonUtils.Error(ctx, http.StatusUnauthorized, "platform_info_not_found", nil)
		return
	}

	// 验证平台类型
	if err := c.validatePlatform(platformInfo.PlatformType); err != nil {
		appErr := err.(*errors.AppError)
		commonUtils.Error(ctx, appErr.Code, appErr.Message, nil)
		return
	}

	// 验证并获取分页参数
	pageIndex, pageSize, err := c.validateAndGetPaginationParams(ctx)
	if err != nil {
		appErr := err.(*errors.AppError)
		commonUtils.Error(ctx, appErr.Code, appErr.Message, nil)
		return
	}

	// 验证查询参数
	if err := c.validateQueryParams(ctx); err != nil {
		appErr := err.(*errors.AppError)
		commonUtils.Error(ctx, appErr.Code, appErr.Message, nil)
		return
	}

	// 构建请求参数
	req := c.buildCardHistoryRequest(ctx, pageIndex, pageSize)

	// 调用平台管理器
	result, err := c.platformManager.HandleRequestWithGinContext(ctx, platformInfo.PlatformType, "card_history_list", req)
	if err != nil {
		commonUtils.Error(ctx, http.StatusInternalServerError, "get_card_history_failed", err)
		return
	}

	// 返回结果
	commonUtils.Success(ctx, gin.H{
		"platform": platformInfo.PlatformType,
		"data":     result,
	})
}

// GetCardHistoryListByPlatform 根据指定平台获取卡历史列表（管理员接口）
func (c *CardHistoryController) GetCardHistoryListByPlatform(ctx *gin.Context) {
	// 获取平台ID参数
	platformID := ctx.Param("platform")
	if platformID == "" {
		commonUtils.Error(ctx, http.StatusBadRequest, "platform_id_required", nil)
		return
	}

	// 验证平台类型
	if err := c.validatePlatform(platformID); err != nil {
		appErr := err.(*errors.AppError)
		commonUtils.Error(ctx, appErr.Code, appErr.Message, nil)
		return
	}

	// 验证并获取分页参数
	pageIndex, pageSize, err := c.validateAndGetPaginationParams(ctx)
	if err != nil {
		appErr := err.(*errors.AppError)
		commonUtils.Error(ctx, appErr.Code, appErr.Message, nil)
		return
	}

	// 验证查询参数
	if err := c.validateQueryParams(ctx); err != nil {
		appErr := err.(*errors.AppError)
		commonUtils.Error(ctx, appErr.Code, appErr.Message, nil)
		return
	}

	// 构建请求参数
	req := c.buildCardHistoryRequest(ctx, pageIndex, pageSize)

	// 调用平台管理器
	result, err := c.platformManager.HandleRequest(ctx.Request.Context(), platformID, "card_history_list", req)
	if err != nil {
		commonUtils.Error(ctx, http.StatusInternalServerError, "get_card_history_failed", err)
		return
	}

	// 返回结果
	commonUtils.Success(ctx, gin.H{
		"platform": platformID,
		"data":     result,
	})
}
